import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:xvideos/hj_page/community_business/hot_up_user/hot_up_user_view.dart';
import 'package:xvideos/hj_page/community_business/widget/community_post_widget.dart';
import 'package:xvideos/hj_utils/widget_utils.dart';
import 'package:xvideos/tools_base/banner/ads_grid_view_widget.dart';
import 'package:xvideos/tools_base/loading/loading_center_widget.dart';
import 'package:xvideos/tools_base/refresh/pull_refresh.dart';

import '../../../hj_model/home/home_tabs_entity.dart';
import '../../../hj_model/video_model.dart';
import '../../../hj_utils/sliver_delegate.dart';
import '../../../tools_base/loading/l_error_widget.dart';
import '../../../tools_base/widget/net_image_widget.dart';
import '../widget/community_middle_header.dart';
import 'community_tab_logic.dart';

class CommunityTabView extends StatelessWidget {
  final ModuleData model;
  final int index;
  final Function()? cancelCallBack;

  const CommunityTabView({
    super.key,
    required this.model,
    this.index = 0,
    this.cancelCallBack,
  });

  @override
  Widget build(BuildContext context) {
    return GetBuilder<CommunityTabLogic>(
      init: CommunityTabLogic(model, index: index),
      global: false,
      builder: (logic) {
        return Container(
          child: pullYsRefresh(
            onInit: (ctr) => logic.refreshController = ctr,
            onRefresh: (_) => logic.fetchPagedata(),
            onLoading: (_) => logic.fetchPagedata(isRefresh: false),
            child: CustomScrollView(
              controller: logic.sctrl,
              slivers: [
                SliverToBoxAdapter(
                  child: AdsGridViewWidget(
                    7,
                    isBigStyle: true,
                    padding: EdgeInsets.fromLTRB(10.w, 10.h, 10.w, 10.h),
                  ),
                ),
                SliverToBoxAdapter(
                  child: _buildSpecialView(logic),
                ),
                SliverPersistentHeader(
                  pinned: true,
                  floating: true,
                  delegate: MySliverDelegate(
                    maxHeight: 40,
                    minHeight: 40,
                    callTop: (shrinkOffset) {
                      if (shrinkOffset > 0) {
                        WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
                          logic.sortMenuIsTop.value = true;
                        });
                      }
                      if (shrinkOffset <= 0) {
                        WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
                          logic.sortMenuIsTop.value = false;
                        });
                      }
                    },
                    child: Obx(
                      () => CommunityMiddleHeader(
                        isInTop: logic.sortMenuIsTop.value,
                        sortOnTap: (sort) {
                          logic.sort = sort;
                          logic.fetchPagedata(needLoading: true);
                        },
                      ),
                    ),
                  ),
                ),
                _buildTableView(logic),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildSpecialView(CommunityTabLogic logic) {
    if (logic.specials.isEmpty) return SizedBox.shrink();
    return GridView.builder(
      physics: NeverScrollableScrollPhysics(),
      padding: EdgeInsets.only(left: 10.w, right: 10.w, bottom: 18.h),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        mainAxisSpacing: 7,
        crossAxisSpacing: 7,
        childAspectRatio: 120 / 57,
      ),
      itemCount: logic.specials.length,
      shrinkWrap: true,
      itemBuilder: (BuildContext context, int index) {
        return InkWell(
          onTap: () {
            logic.tagIndex = index;
            logic.tagId = logic.specials[index].id;
            logic.fetchPagedata(needLoading: true);
          },
          child: _buildSpecialTagCell(logic, index),
        );
      },
    );
  }

  Widget _buildSpecialTagCell(CommunityTabLogic logic, int index) {
    TagsBean model = logic.specials[index];
    return Stack(
      fit: StackFit.expand,
      children: [
        Container(
          decoration: logic.tagIndex == index
              ? BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(6)),
                  border: Border.all(
                    color: const Color(0xffffffff),
                    width: 2,
                  ))
              : BoxDecoration(
                  color: Color(0x00FFFFFF),
                ),
          padding: EdgeInsets.only(bottom: 0),
          child: Stack(
            fit: StackFit.expand,
            children: [
              NetworkImageLoader(
                imageUrl: model.coverImg ?? '',
                borderRadius: 6,
                width: double.infinity,
                height: double.infinity,
              ),
              Container(
                decoration: BoxDecoration(borderRadius: BorderRadius.circular(6), color: Colors.black.withOpacity(.6)),
              ),
              if (model.hotMark?.isNotEmpty == true)
                Positioned(
                  top: 0,
                  left: 0,
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 3, vertical: 1),
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        colors: [
                          Color.fromRGBO(252, 118, 118, 1),
                          Color.fromRGBO(212, 39, 39, 1),
                        ],
                      ),
                      borderRadius: BorderRadius.only(
                        bottomRight: Radius.circular(6),
                        topLeft: Radius.circular(6),
                      ),
                    ),
                    child: Text(
                      "${model.hotMark}",
                      style: TextStyle(color: Colors.white, fontSize: 11),
                    ),
                  ),
                ),
            ],
          ),
        ),
        Container(
          child: Stack(
            fit: StackFit.expand,
            children: [
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    "${model.tagName}",
                    style: TextStyle(
                        color: logic.tagIndex == index ? Color(0xFF3476ff) : Colors.white, fontSize: 14, fontWeight: FontWeight.bold),
                  ),
                  2.sizeBoxH,
                  Text(
                    "${model.videoCount.humanizeFormat}个帖子",
                    style: TextStyle(color: logic.tagIndex == index ? Color(0xFF3476ff) : Colors.white, fontSize: 12),
                  ),
                ],
              ),
              // if (model.hotMark?.isNotEmpty == true)
              //   Positioned(
              //     top: 0,
              //     left: 0,
              //     child: Container(
              //       decoration: BoxDecoration(
              //         gradient: LinearGradient(
              //           colors: [
              //             Color.fromRGBO(252, 118, 118, 1),
              //             Color.fromRGBO(212, 39, 39, 1),
              //           ],
              //         ),
              //         borderRadius: BorderRadius.only(
              //           bottomRight: Radius.circular(6),
              //           topLeft: Radius.circular(6),
              //         ),
              //       ),
              //       width: 26,
              //       height: 14,
              //       alignment: Alignment.center,
              //       child: Text(
              //         "${model.hotMark}",
              //         style: TextStyle(color: Colors.white, fontSize: 11),
              //       ),
              //     ),
              //   ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildTableView(CommunityTabLogic logic) {
    if (logic.isLoading)
      return SliverToBoxAdapter(
        child: SizedBox(
          height: 300,
          child: LoadingCenterWidget(),
        ),
      );
    if (logic.dataSource.isEmpty)
      return SliverToBoxAdapter(
        child: SizedBox(
          height: 300,
          child: CErrorWidget(
            retryOnTap: () => logic.fetchPagedata(),
          ),
        ),
      );

    return SliverPadding(
      padding: EdgeInsets.only(top: 10),
      sliver: SliverList.separated(
        separatorBuilder: (_, __) => 0.h.sizeBoxH,
        itemBuilder: (BuildContext context, int index) {
          VideoModel videoModel = logic.dataSource[index];
          if (videoModel.isHotUp()) {
            return HotUpUserView(hotUpList: videoModel.hotUpList);
          } else {
            return CommunityPostWidget(videoModel: videoModel, videoModels: logic.dataSource);
          }
        },
        itemCount: logic.dataSource.length,
      ),
    );
  }
}
